import Xlsx from 'js-xlsx';

export class FileReaderXlsx {
    static reader(file, callback) {
        const reader = new FileReader();
        let rABS = '';
        let wb = '';
        const XLSX = Xlsx;
        reader.onload = function(e) {
            var data = e.target.result;
            if (rABS) {
                wb = XLSX.read(btoa(FileReaderXlsx.fixdata(data)), {
                    //手动转化
                    type: 'base64',
                });
            } else {
                wb = XLSX.read(data, {
                    type: 'binary',
                });
            }
            callback(
                XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]),
                XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[1]]),
            );
        };
        if (rABS) {
            reader.readAsArrayBuffer(file);
        } else {
            reader.readAsBinaryString(file);
        }
    }

    static fixdata(data) {
        //文件流转BinaryString
        var o = '',
            l = 0,
            w = 10240;
        for (; l < data.byteLength / w; ++l)
            o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w, l * w + w)));
        o += String.fromCharCode.apply(null, new Uint8Array(data.slice(l * w)));
        return o;
    }
}
